from flask import Flask

from test import apiModel
from models.model import db
from flask_restful import Api
from register_api import api_list


def create_app(object_name):
    application = Flask(__name__)
    application.config.from_object(object_name)
    db.init_app(application)
    # 蓝图注册到app
    application.register_blueprint(apiModel)
    application.after_request(after_request)
    # 设置请求内容的大小限制，即限制了上传文件的大小
    application.config['MAX_CONTENT_LENGTH'] = 5 * 1024 * 1024
    application = add_apis(application=application)
    # 对celery进行初始化操作，可以将celery的配置写在app的配置中
    # celery.init_app(app=application)
    return application


# 跨域支持
def after_request(resp):
    resp.headers['Access-Control-Allow-Origin'] = 'http://192.168.20.200:8090'
    resp.headers['Access-Control-Allow-Credentials'] = 'true'
    resp.headers['Access-Control-Allow-Methods'] = ['GET', 'POST']
    resp.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return resp


def add_apis(application):
    rest_api = Api()
    for i in api_list:
        rest_api.add_resource(i[0], i[1])
    rest_api.init_app(application)
    return application
